package com.caption.auth.secuity.username;

import com.caption.auth.model.entity.SysRole;
import com.caption.auth.model.entity.SysUser;
import com.caption.auth.secuity.constant.SecurityConstant;
import com.caption.auth.secuity.entity.SysUserDetails;
import com.caption.auth.service.SysUserService;
import com.caption.core.model.enums.BaseResultEnum;
import com.caption.core.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * @description: 加载用户账号、密码、权限
 * @author: 码农
 * @date: 2021-12-31 20:11:15
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public SysUserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getParameter(SecurityConstant.LOGIN_TYPE);
        if (StringUtils.isAnyBlank(loginType)) {
            throw new ServiceException(BaseResultEnum.MISSING_REQUIRED_ARGUMENTS);
        }

        SysUser sysUser = sysUserService.selectByUserName(username);
        if (Objects.isNull(sysUser)) {
            return null;
        }
        SysUserDetails sysUserDetails = new SysUserDetails();
        BeanUtils.copyProperties(sysUser, sysUserDetails);
        List<SysRole> sysRoles = sysUserService.selectRoleByUserId(sysUser.getId());
        sysUserDetails.setRoles(sysRoles);
        //用户权限可以考虑不添加
        return sysUserDetails;
    }



}
